// import Vue from 'vue'
import store from '@/store'
import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/components/storybook/router'
import qs from 'qs'
import { clearLoginInfo, rememberRoute } from '@/utils'
import { isPlainObject } from 'lodash'

const http = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  timeout: 1000 * 180,
  withCredentials: true
})

http.interceptors.request.use(config => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  config.headers['token'] = Cookies.get('token') || ''
  config.headers['tenantCode'] = Cookies.get('tenant_code') || ''
  config.headers['loginAsRoleId'] = sessionStorage.getItem('loginAsRoleId') ? sessionStorage.getItem('loginAsRoleId') : ''
  config.headers['loginAsUserId'] = sessionStorage.getItem('loginAsUserId') ? sessionStorage.getItem('loginAsUserId') : ''
  config.headers['timezoneOffset'] = store.state.user.timezoneOffset ? store.state.user.timezoneOffset : ''
  config.headers['timezoneId'] = store.state.user.timezoneId ? store.state.user.timezoneId : ''
  var defaults = {}
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{ '_t': new Date().getTime() }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }
  return config
}, error => {
  return Promise.reject(error)
})

http.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.code === 10001) {
    const tempRouter = store.state.contentTabs
    clearLoginInfo()
    rememberRoute(tempRouter)
    if (window.location.pathname !== '/login' && window.location.pathname !== '/loginAsAccount') {
      if (!store.state.app.beforeLoginPage) store.state.app.beforeLoginPage = window.location.pathname
      if (!store.state.app.beforeLoginParams) store.state.app.beforeLoginParams = window.location.search
    }
    store.state.app.isNavToLogin = true

    router.replace({
      name: 'login'
    })

    return Promise.reject(response.data.msg)
  }
  if (response.status !== 200) {
    return Promise.reject(response)
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default http
